import React from 'react'
import {connect} from 'react-redux'
import {List,Badge} from 'antd-mobile'
import {messageRead} from '../../redux/chat.redux'
@connect(
  state=>state,
  {messageRead}
)
class Msg extends React.Component{
  render(){
    const msgGroup = {}
    this.props.chat.chatmsg.forEach(v=>{
      msgGroup[v.chatid] = msgGroup[v.chatid] || []
      msgGroup[v.chatid].push(v)
    })
    // console.log(msgGroup)
    // const chatList = Object.values(msgGroup)
    const Brief = List.Item.Brief
    const userid = this.props.user._id
    const chatList = Object.values(msgGroup).sort((a,b)=>{
      const a_last = a[a.length-1].create_time
      const b_last = b[b.length-1].create_time
      return b_last - a_last
    })
    return (
      <div>
        <List>
          {chatList.map(v=>{
            const chatid = v[0].chatid
            const targetId = v[0].from === userid ? v[0].to : v[0].from
            const unreadNum = v.filter(v=>!v.read && v.to===userid).length
            console.log(targetId)
            return (<List.Item
              extra={<Badge text={unreadNum}></Badge>} 
              thumb={require(`../../component/imgs/${this.props.chat.users[targetId].avatar}.png`)}
              arrow="horizontal"
              onClick={()=>{
                this.props.history.push(`/chat/${targetId}`)
                // this.props.messageRead(chatid)
              }}
              key={v[0]._id}>
              {v[v.length-1].content}
              <Brief>{this.props.chat.users[targetId].name}</Brief>
            </List.Item>)
          })}
        </List>
      </div>
    )
  }
}
export default Msg